package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.domain.constant.EsConstant;
import com.hmall.domain.constant.MqConstant;
import com.hmall.domain.doc.ItemDoc;
import com.hmall.domain.pojo.Item;
import com.hmall.feign.common.ItemFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 商品item mq的监听类
 *
 * @Author XiaoJiangShi
 * @Date 2022/8/11 17:20
 * @Blog blog.XiaoJiangShi.net/996.mba
 * @Description: 商品mq的监听类
 */
@Slf4j
@Component
public class ItemSearchListener {

    @Autowired
    private ItemFeignClient feignClient;
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(MqConstant.ITEM_INSERT_QUEUE),
                    exchange = @Exchange(MqConstant.ITEM_EXCHANGE),
                    key = MqConstant.ITEM_INSERT_ROUT)
    })
    public void update(String id) {
        try {
            Item byId = feignClient.findById(Long.parseLong(id));
            ItemDoc itemDoc = new ItemDoc(byId);
            IndexRequest request = new IndexRequest(EsConstant.ITEM_INDEX);
            request.id(id);
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(MqConstant.ITEM_DELETE_QUEUE),
                    exchange = @Exchange(MqConstant.ITEM_EXCHANGE),
                    key = MqConstant.ITEM_DELETE_ROUT)
    })
    public void delete(String id) {
        try {
            DeleteRequest request = new DeleteRequest(EsConstant.ITEM_INDEX, id);
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

